package leetcode.f1t100;

import java.util.ArrayList;
import java.util.List;

/**
 * 插入区间后合并
 * https://leetcode.com/problems/insert-interval/
 *
 * @Author lichongxiao
 * @Date 2022/10/25 11:27
 */
public class Q57_InsertInterval {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> ansList = new ArrayList<>();
        boolean flag = false;
        for (int[] interval : intervals) {
            if(flag){
                ansList.add(interval);
                continue;
            }
            if (interval[0] > newInterval[1]) {
                ansList.add(newInterval);
                ansList.add(interval);
                flag = true;
            } else if (interval[1] < newInterval[0]) {
                ansList.add(interval);
            } else {
                newInterval[0] = Math.min(interval[0],newInterval[0]);
                newInterval[1] = Math.max(interval[1],newInterval[1]);
            }
        }
        if (!flag) {
            ansList.add(newInterval);
        }
        return ansList.toArray(new int[0][]);
    }

}
